package org.je.database.impl;

import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.je.cons.JCons;
import org.je.log.JLog;
import org.je.util.DynBuffer;
import org.je.xml.Element;
import org.je.xml.XUtil;

/**
 * @author fanyifeng 2012-10-16 上午10:56:48
 */
public class StaticConfig
{

	/**
	 * @param i
	 * @return dataSource
	 */
	public static DataSource getDataSource(int i) {
		init();
		return dataSourceList.get(i);
	}

	public static int sizeOfDataSource() {
		init();
		return dataSourceList.size();
	}

	/**
	 * private ....
	 */
	private static List<DataSource>	dataSourceList	= new ArrayList<DataSource>(1);
	private static volatile boolean	isInit			= false;
	private static final Object		initLock		= new Object();

	private static void init() {
		if (isInit) {
			return;
		}
		synchronized(initLock) {
			if (isInit) {
				return;
			}
			doInit();
			isInit = true;
		}
	}

	private static void doInit() {
		DynBuffer bf = new DynBuffer();
		try {
			InputStream in = StaticConfig.class.getResourceAsStream("/database_config.xml");
			byte[] tem = new byte[256];
			while (true) {
				int len = in.read(tem);
				if (len < 0) {
					break;
				}
				bf.append(tem, 0, len);
			}
		} catch (Exception ex) {
			JLog.error(ex);
			throw new RuntimeException("read-database-config-error ", ex);
		}

		String xml=null;
		try {
			xml = new String(bf.toArray(), JCons.enc().utf8);
		} catch (UnsupportedEncodingException ex) {
			throw new RuntimeException(ex);
		}
		Element root = XUtil.parse(xml);
		List<Element> sourceList = root.getElementsByTagName("dataSource");

		for (Element ds : sourceList) {
			parseSource(ds);
		}
	}

	private static void parseSource(Element ds) {
		DataSource source = new DataSource();
		source.id = ds.getAtt("id");
		source.driver = ds.getFirst("driver").getFirst().toString();
		source.connectionString = ds.getFirst("connectionString").getFirst().toString();
		source.user = ds.getFirst("user").getFirst().toString();
		source.pwd = ds.getFirst("pwd").getFirst().toString();
		source.connectionCount = Integer.parseInt(ds.getFirst("connectionCount").getFirst().toString());
		source.connectionLevel = Integer.parseInt(ds.getFirst("connectionLevel").getFirst().toString());
		source.testSql = ds.getFirst("testSql").getFirst().toString();
		source.showSql = "true".equals(ds.getFirst("showSql").getFirst().toString());
		source.showResult = "true".equals(ds.getFirst("showResult").getFirst().toString());
		source.maxShowCount = Integer.parseInt(ds.getFirst("maxShowCount").getFirst().toString());
		dataSourceList.add(source);
	}
}
